using MediatR;
using RBAC.Domain.Approval;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Approval;

namespace RBAC.Write.Api.Application.Handler.Approval
{
    /// <summary>
    /// 删除审批流程处理器
    /// </summary>
    public class DeleteApprovalProcessHandler : IRequestHandler<DeleteApprovalProcessCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ApprovalProcess> approvalProcessRepository;
        private readonly IBaseRepository<ApprovalNode> approvalNodeRepository;
        private readonly IBaseRepository<ApprovalInstance> approvalInstanceRepository;
        private readonly ILogger<DeleteApprovalProcessHandler> logger;

        public DeleteApprovalProcessHandler(
            IBaseRepository<ApprovalProcess> approvalProcessRepository,
            IBaseRepository<ApprovalNode> approvalNodeRepository,
            IBaseRepository<ApprovalInstance> approvalInstanceRepository,
            ILogger<DeleteApprovalProcessHandler> logger)
        {
            this.approvalProcessRepository = approvalProcessRepository;
            this.approvalNodeRepository = approvalNodeRepository;
            this.approvalInstanceRepository = approvalInstanceRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 处理删除审批流程命令
        /// </summary>
        /// <param name="request">删除审批流程命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API结果</returns>
        public async Task<APIResult<int>> Handle(DeleteApprovalProcessCommand request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("开始删除审批流程，ID: {Id}", request.Id);

                // 查找现有的审批流程（排除已删除的）
                var existingProcess = approvalProcessRepository.GetALL()
                    .FirstOrDefault(x => x.Id == request.Id && !x.IsDeleted);

                if (existingProcess == null)
                {
                    logger.LogWarning("未找到审批流程，ID: {Id}", request.Id);
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "未找到指定的审批流程",
                        Data = 0
                    };
                }

                // 检查是否有进行中的审批实例
                var pendingInstances = approvalInstanceRepository.GetALL()
                    .Where(x => x.ProcessId == request.Id && x.Status == 1)
                    .ToList();

                if (pendingInstances.Any())
                {
                    logger.LogWarning("审批流程存在进行中的实例，无法删除，ID: {Id}", request.Id);
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "该审批流程存在进行中的审批实例，无法删除",
                        Data = 0
                    };
                }

                // 逻辑删除相关的审批节点
                var approvalNodes = approvalNodeRepository.GetALL()
                    .Where(x => x.ProcessId == request.Id && !x.IsDeleted)
                    .ToList();

                foreach (var node in approvalNodes)
                {
                    node.IsDeleted = true;
                    approvalNodeRepository.Update(node);
                }

                // 逻辑删除审批流程
                existingProcess.IsDeleted = true;
                var result = approvalProcessRepository.Update(existingProcess);

                if (result > 0)
                {
                    logger.LogInformation("审批流程逻辑删除成功，ID: {Id}，删除节点数: {NodeCount}", 
                        request.Id, approvalNodes.Count);
                    return new APIResult<int>
                    {
                        Code = APIEnums.Success,
                        Msg = "审批流程删除成功",
                        Data = result
                    };
                }
                else
                {
                    logger.LogError("审批流程逻辑删除失败，ID: {Id}", request.Id);
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "审批流程删除失败",
                        Data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "逻辑删除审批流程时发生异常，ID: {Id}", request.Id);
                return new APIResult<int>
                {
                    Code = APIEnums.Error,
                    Msg = $"删除审批流程失败：{ex.Message}",
                    Data = 0
                };
            }
        }
    }
}
